package com.gzc.just.play.last.war.common.message.handler;

import com.gzc.just.play.last.war.common.inventory.InventoryManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Item use message handler
 */
@Component
public class ItemUseHandler implements MessageHandlerInterface {

    private static final Logger log = LoggerFactory.getLogger(ItemUseHandler.class);

    private final InventoryManager inventoryManager;
    private final ObjectMapper objectMapper;
    
    public ItemUseHandler(InventoryManager inventoryManager, ObjectMapper objectMapper) {
        this.inventoryManager = inventoryManager;
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(Long playerId, Object messageData) {
        try {
            // Parse item data
            Map<String, Object> itemData = objectMapper.convertValue(messageData, Map.class);
            
            Long itemId = Long.valueOf(itemData.get("itemId").toString());
            Integer quantity = (Integer) itemData.getOrDefault("quantity", 1);
            Long targetId = itemData.containsKey("targetId") ? 
                Long.valueOf(itemData.get("targetId").toString()) : null;
            
            // Check if player has this item
            if (!inventoryManager.hasItem(playerId, itemId, quantity)) {
                log.warn("Player {} does not have enough of item {}: {}", playerId, itemId, quantity);
                return;
            }
            
            // Use item
            boolean success = inventoryManager.useItem(playerId, itemId, quantity, targetId);
            
            if (success) {
                log.info("Player {} used item {} (quantity: {})", playerId, itemId, quantity);
            } else {
                log.warn("Failed to use item {} for player {}", itemId, playerId);
            }
        } catch (Exception e) {
            log.error("Error processing item use for player: {}", playerId, e);
        }
    }
}